# coding:utf-8
from sqlalchemy import Column, String, Integer, DateTime, Date, and_

from database import dbconnect, session_maker, model_list

_, _, DBase = dbconnect()


class CmsEcsDisk(DBase):
    __tablename__ = 'cms_ecs_disk'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    instance_id = Column(String(255))
    cloud_id = Column(Integer)
    department = Column(String(255))
    department_name = Column(String(255))
    device = Column(String(255))
    disk_usage = Column(String(255))
    disk_size = Column(Integer)
    disk_id = Column(String(255))
    date = Column(Date)
    record_time = Column(DateTime)


def get_period_ecs_disk_cms(start, end) -> dict:
    """
    获取时间段内，所有ECS Disk的信息，并生成一个字典：
    {
        "<instance-id-001>":{
            "current_size" : 100,
            "period_stats": {'total_size': xx, 'total_used': xx, 'total_usage': xx},
            "daily_info" :{
                "2023-09-21": {
                    'total_size': '100',
                    'total_used': '55.45',
                    'total_usage': '55.45',
                    'devices': {
                        '/dev/vda1' : {'size' :40, 'usage': '20.45',},
                        '/dev/vdb1' : {'size' :100, 'usage': '88.45',},
                    }
                },
                "2023-09-20": {
                    'total_size': '100',
                    'total_used': '55.45'
                    'total_usage': '55.45'
                    'devices': {
                        '/dev/vda1' : {'size' :40, 'usage': '20.45',},
                        '/dev/vdb1' : {'size' :100, 'usage': '88.45',},
                    }
                }
            }
        }
    }
    :param start:
    :param end:
    :return:
    """
    disk_cms_dt = {}
    date_list = []
    with session_maker() as session:
        result = session.query(CmsEcsDisk).filter(and_(
            CmsEcsDisk.date >= start,
            CmsEcsDisk.date < end
        )).order_by(CmsEcsDisk.date.desc()).all()  # 记录时间倒序，这样首次出现的实例信息，被记为最新信息
        #

        for row in model_list(result):
            tmp_date = str(row['date'])
            date_list.append(tmp_date)
            tmp_ins_id = row['instance_id']
            tmp_disk_id = row['disk_id']
            tmp_device = row['device']
            tmp_disk_size = int(row['disk_size'])
            tmp_disk_usage = float(row['disk_usage'])

            # 实例ID不存在，则初始化实例信息
            if tmp_ins_id not in disk_cms_dt.keys():
                disk_cms_dt[tmp_ins_id] = {
                    "current_size": tmp_disk_size,
                    "period_stats": {'total_size': 0, 'total_used': 0, 'total_usage': 0},
                    'daily_info': {}
                }

            # 当前日期不存在，则初始化该日期
            if tmp_date not in disk_cms_dt[tmp_ins_id]['daily_info'].keys():
                disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date] = {
                    'total_size': 0,
                    'total_used': 0,
                    'total_usage': 0,
                    'devices': {}
                }

            # 当日device信息不存在，则记录之
            if tmp_device not in disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['devices'].keys():
                disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['devices'][tmp_device] = {
                    'size': tmp_disk_size, 'usage': tmp_disk_usage
                }

                # 计算当日总量
                disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['total_size'] += tmp_disk_size
                disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['total_used'] += (tmp_disk_size * tmp_disk_usage)
                disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['total_usage'] = \
                    disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['total_used'] / \
                    disk_cms_dt[tmp_ins_id]['daily_info'][tmp_date]['total_size']

                # 计算阶段总量
                disk_cms_dt[tmp_ins_id]['period_stats']['total_size'] += tmp_disk_size
                disk_cms_dt[tmp_ins_id]['period_stats']['total_used'] += (tmp_disk_size * tmp_disk_usage)
                disk_cms_dt[tmp_ins_id]['period_stats']['total_usage'] = \
                    disk_cms_dt[tmp_ins_id]['period_stats']['total_used'] / \
                    disk_cms_dt[tmp_ins_id]['period_stats']['total_size']

    print("get_disk_info dates: ", set(date_list))

    return disk_cms_dt


if __name__ == '__main__':
    a = get_period_ecs_disk_cms("2023-09-01","2023-09-30")
    print(a)